package com.itheima.admin.controller;

import com.itheima.admin.dto.ChannelPageDto;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.admin.service.AdChannelService;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.vo.PageResultVo;
import com.itheima.common.vo.ResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/channel")
@Api(tags = "频道列表")
public class AdChannelController {

    @Autowired
    private AdChannelService adChannelService;

    /**
     * 分页查询频道列表
     *
     * @param dto
     * @return
     */
    @PostMapping("/list")
    @ApiOperation(value = "分页查询频道列表")
    public PageResultVo<AdChannel> pageList(@RequestBody ChannelPageDto dto) {
        PageResultVo<AdChannel> pageList = adChannelService.pageList(dto);

        return pageList;
    }


    /**
     * 新增频道
     *
     * @param adChannel
     * @return
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增频道")
    public ResultVo<AdChannel> save(@RequestBody AdChannel adChannel) {
        if (adChannel == null || adChannel.getName() == null) {
            return ResultVo.error(HttpCodeEnum.PARAM_REQUIRE);
        }

        adChannel.setCreatedTime(new Date());
        adChannel.setIsDefault(true);

        if (adChannelService.save(adChannel)) {
            return ResultVo.ok();
        }
        return ResultVo.error();
    }

    /**
     * 查询当前id的数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询")
    public ResultVo<AdChannel> findById(@PathVariable Integer id){
       return ResultVo.ok(adChannelService.getById(id));

    }


    /**
     * 更新频道
     *
     * @param adChannel
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("更新频道")
    public ResultVo<AdChannel> update(@RequestBody AdChannel adChannel) {
        if (adChannel == null || adChannel.getId() == null) {
            return ResultVo.error(HttpCodeEnum.PARAM_REQUIRE);
        }

        adChannel.setCreatedTime(new Date());

        if (adChannelService.updateById(adChannel)) {
            return ResultVo.ok();
        }
        return ResultVo.error();
    }

    /**
     * 删除频道
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation("删除频道")
    public ResultVo<AdChannel> delete(@PathVariable Integer id) {

        if (adChannelService.removeById(id)) {
            return ResultVo.ok();
        }
        return ResultVo.error();
    }


}


